package org.overtheair.say.ui;

import org.overtheair.say.logic.DataProviderFlickr;
import org.overtheair.say.logic.DataProviderMovie;
import org.overtheair.say.logic.DataProviderUpcoming;
import org.overtheair.say.logic.DataStore;

import org.overtheair.say.common.GlobalHelper;
import org.overtheair.say.domain.QueryType;

import org.overtheair.say.R;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;


public class FrmMain
	extends Activity
	implements LocationListener, RadioGroup.OnCheckedChangeListener
{
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.frmmain);
        
        initTasks();
    }

   
    
	// ************************************************************************
	// Events area
	// ************************************************************************

	/**
	 * Create an anonymous implementation of OnClickListener
	 */
	private OnClickListener btnDisplayData_Click = new OnClickListener() {
		public void onClick(View v) {
			CheckBox chkbox;
			
			//check what data display
			chkbox = (CheckBox) findViewById(R.id.frmMain_chkPhotos);
			mDataStore.photosEnabled = chkbox.isChecked();
			chkbox = (CheckBox) findViewById(R.id.frmMain_chkEvents);
			mDataStore.eventsEnabled = chkbox.isChecked();
//			chkbox = (CheckBox) findViewById(R.id.frmMain_chkMovies);
//			mDataStore.moviesEnabled = chkbox.isChecked();
			
			WikitudeAPIProvider.startARViewBasic(FrmMain.this, mDataStore);
		}
	};

	// Create an anonymous implementation of OnClickListener
	private OnClickListener btnGetData_Click = new OnClickListener() {
		public void onClick(View v) {
			Location loc;
			RadioButton radioBtn;
			QueryType queryType;
			double latitude;
			double longitude;
			String fixedLocation;

			//choose the correct updating filter
			radioBtn = (RadioButton) findViewById(R.id.frmMain_radioCurrenLocation);
			if (radioBtn.isChecked())
			{
				loc = getCurrentLocation();

				//checks if current location is available
				if (null == loc)
				{
					queryType = QueryType.None;
					fixedLocation = "";
					latitude = 0;
					longitude = 0;
				}
				else
				{
					//filter by current location
					queryType = QueryType.CurrentLocation;
					fixedLocation = "";
					latitude = loc.getLatitude();
					longitude = loc.getLongitude();
				}
			}
			else
			{
				//filter by fixed location
				queryType = QueryType.FixedLocation;
				EditText editTxt = (EditText) findViewById(R.id.frmMain_txtLocationName);
				fixedLocation = editTxt.getText().toString();
				latitude = 0;
				longitude = 0;
			}
			
			if (queryType == QueryType.None)
			{
				Toast.makeText(getApplicationContext(), "Sorry, your current position is not available", Toast.LENGTH_LONG).show();
			}
			else
			{
				//update the photos datasource
				updatePhotosSource(queryType, latitude, longitude, fixedLocation);
				//doesn't work, so no update
				updateEventsSource(queryType, latitude, longitude, fixedLocation);
				//doesn't work, so no update
				//updateMoviesSource(queryType, latitude, longitude, fixedLocation);
			}
		}
	};
	

	/**
	 * Radio button listener
	 */
	public void onCheckedChanged(RadioGroup group, int checkedId)
	{
		EditText editTxt;

		editTxt = (EditText) findViewById(R.id.frmMain_txtLocationName);
		if (checkedId == R.id.frmMain_radioCurrenLocation)
		{
			editTxt.setEnabled(false);
		}
		else
		{
			//little hack
			editTxt.setEnabled(true);
		}
	}



	// ************************************************************************
	// Private properties
	// ************************************************************************
	/** Location Manager */
	private LocationManager mLocationManager;
	/** Current location */
	private Location mCurrentLocation;
	/** selected location provider */
	private String mLocationProviderKey;
	/** data storage */
	private DataStore mDataStore;




	//*************************************************************************
    // private methods
    //*************************************************************************
	private void initTasks() {
		Button button;
		CheckBox chkBox;
		EditText txtEdit;

		//initialize location provider
		initLocation();
		
		mDataStore = new DataStore();
		
		// registers handlers
		button = (Button) findViewById(R.id.frmMain_btnDisplayData);
		// Register the onClick listener with the implementation above
		button.setOnClickListener(btnDisplayData_Click);
		
		button = (Button) findViewById(R.id.frmMain_btnGetData);
		// Register the onClick listener with the implementation above
		button.setOnClickListener(btnGetData_Click);
	
		//disable checkbox visibility
		chkBox = (CheckBox) findViewById(R.id.frmMain_chkPhotos);
		chkBox.setChecked(false);
		chkBox.setEnabled(false);
		chkBox = (CheckBox) findViewById(R.id.frmMain_chkEvents);
		chkBox.setChecked(false);
		chkBox.setEnabled(false);
//		chkBox = (CheckBox) findViewById(R.id.frmMain_chkMovies);
//		chkBox.setChecked(false);
//		chkBox.setEnabled(false);
		
		//disable location area visibility
		txtEdit = (EditText) findViewById(R.id.frmMain_txtLocationName);
		txtEdit.setEnabled(false);
		
        RadioGroup radioGrp = (RadioGroup) findViewById(R.id.frmMain_group1);
        radioGrp.setOnCheckedChangeListener(this); 
	}



	
	// ************************************************************************
	// LocationListener implementation and utilities
	// ************************************************************************

	//update current location and display it on the map
	public void onLocationChanged(Location location) {
		//save the location read
		if (location != null) {
			mCurrentLocation = location;
			TextView txtLocation = (TextView) findViewById(R.id.frmMain_lblLocation);
			txtLocation.setText(String.format("Location: %f, %f", mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude()));
		}
	}

	public void onProviderDisabled(String provider) {
		// TODO Auto-generated method stub
	}

	public void onProviderEnabled(String provider) {
		// TODO Auto-generated method stub
	}

	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub
	}	
	
	/**
	 * Initialize best location provider and register it for getting position
	 */
	private void initLocation() {
		//get the location provider
		this.mLocationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
		
		//reset current location
		mCurrentLocation = null;

		//find the best provider available
        mLocationProviderKey = this.mLocationManager.getBestProvider(new Criteria(), true);

        if (GlobalHelper.IsNullOrEmpty(mLocationProviderKey))
        	return;

		//and register the best provider for updating position
		mLocationManager.requestLocationUpdates(mLocationProviderKey, 2000L, 500.0f, this);
	}
	

	private Location getCurrentLocation()
	{
		Location locToDisplay;

		//check current location
		if (null == mCurrentLocation)
		{
			//try to get the last know position
			locToDisplay = mLocationManager.getLastKnownLocation(mLocationProviderKey);
		}
		else
			locToDisplay = mCurrentLocation;
		
		return locToDisplay;		
	}


	private void updatePhotosSource(QueryType queryType, double latitude, double longitude, String fixedLocation)
	{
		CheckBox chkBox;
		ProgressDialog pd;

		//start progress dialog
		pd = ProgressDialog.show(FrmMain.this, "", "Retrieve photos... Please wait, it's the #OTA09 alpha ;)", true);
		
		//load photos into datastore
		if (queryType == QueryType.CurrentLocation)
			mDataStore.photos = DataProviderFlickr.getFlickrPhotos(latitude, longitude);
		else
			mDataStore.photos = DataProviderFlickr.getFlickrPhotos(fixedLocation);

		//update photo checkbox status
		chkBox = (CheckBox) findViewById(R.id.frmMain_chkPhotos);
		chkBox.setText(R.string.frmMain_chkPhotos);
		if (mDataStore.photos.size() > 0)
		{
			//enable photos checkbox
			chkBox.setText(
					chkBox.getText() + 
					" (" + 
					new Integer(mDataStore.photos.size()).toString() +
					")");
			chkBox.setEnabled(true);
			chkBox.setSelected(true);
		}
		else
		{
			//disable photos checkbox
			chkBox.setEnabled(false);
			chkBox.setSelected(false);
		}
		pd.dismiss();
	}


	private void updateEventsSource(QueryType queryType, double latitude, double longitude, String fixedLocation)
	{
		CheckBox chkBox;
		ProgressDialog pd;

		//start progress dialog
		pd = ProgressDialog.show(FrmMain.this, "", "Retrieve events... Please wait, it's the #OTA09 alpha ;)", true);
		
		//load events into datastore
		if (queryType == QueryType.CurrentLocation)
			mDataStore.events = DataProviderUpcoming.getUpcomingEvents(latitude, longitude);
		else
			mDataStore.events = DataProviderUpcoming.getUpcomingEvents(fixedLocation);

		//update events checkbox status
		chkBox = (CheckBox) findViewById(R.id.frmMain_chkEvents);
		chkBox.setText(R.string.frmMain_chkEvents);
		if (mDataStore.events.size() > 0)
		{
			//enable photos checkbox
			chkBox.setText(
					chkBox.getText() + 
					" (" + 
					new Integer(mDataStore.events.size()).toString() +
					")");
			chkBox.setEnabled(true);
			chkBox.setSelected(true);
		}
		else
		{
			//disable photos checkbox
			chkBox.setEnabled(false);
			chkBox.setSelected(false);
		}
		pd.dismiss();
	}

	private void updateMoviesSource(QueryType queryType, double latitude, double longitude, String fixedLocation)
	{
//		CheckBox chkBox;
//		ProgressDialog pd;
//
//		//start progress dialog
//		pd = ProgressDialog.show(FrmMain.this, "", "Retrieve photos... Please wait, it's the #OTA09 alpha ;)", true);
//		
//		//load photos into datastore
//		if (queryType == QueryType.CurrentLocation)
//			mDataStore.movies = DataProviderMovie.getMovies(latitude, longitude);
//		else
//			mDataStore.movies = DataProviderMovie.getMovies(fixedLocation);
//
//		//update photo checkbox status
//		chkBox = (CheckBox) findViewById(R.id.frmMain_chkMovies);
//		chkBox.setText(R.string.frmMain_chkMovies);
//		if (mDataStore.movies.size() > 0)
//		{
//			//enable photos checkbox
//			chkBox.setText(
//					chkBox.getText() + 
//					" (" + 
//					new Integer(mDataStore.movies.size()).toString() +
//					")");
//			chkBox.setEnabled(true);
//			chkBox.setSelected(true);
//		}
//		else
//		{
//			//disable photos checkbox
//			chkBox.setEnabled(false);
//			chkBox.setSelected(false);
//		}
//		pd.dismiss();
	}
	
}